/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;


import com.tinyline.util.GZIPInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

public class FileUtility {

    /**
     * membaca file
     * @param pathFile
     * @return
     */
    public static String readFile(String pathFile) {
        String hasil=null;
        try {
            FileConnection fileToRead = (FileConnection) Connector.open(pathFile,Connector.READ);
            InputStream is = fileToRead.openInputStream();
            hasil = convertInputstreamToString(is);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return hasil;
    }

    /**
     * membaca file GZIP
     * @param pathFile
     * @return
     */
    public static String readFileCompressed(String pathFile) {
        String hasil=null;
        try {
            FileConnection fileToRead = (FileConnection) Connector.open(pathFile,Connector.READ);
            InputStream is = fileToRead.openInputStream();
            hasil = convertInputstreamToString(new GZIPInputStream(is));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return hasil;
    }

    /**
     * menulis file
     * @param pathFile
     * @param data
     * @return
     */
    public static boolean writeFile(String pathFile, byte[] data) {
        FileConnection c = null;
        OutputStream os = null;
        try {
            FileConnection fc = (FileConnection) Connector.open(pathFile, Connector.READ_WRITE);
            if (!fc.exists()) {
                fc.create();
            } else {
                fc.truncate(0);
            }
            os = fc.openOutputStream();
            os.write(data);
            os.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (c != null) {
                    c.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }


    public static String convertInputstreamToString(InputStream is) {
        StringBuffer sb = new StringBuffer();
        try {
            int chars, i = 0;
            while ((chars = is.read()) != -1) {
                sb.append((char) chars);
            }
            return sb.toString();
        } catch (Exception e) {
        }
        return null;
    }
}
